package com.anrongtec.zcpt.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.JsonDataRestult;
import com.anrongtec.zcpt.constant.URLConstants;
import com.anrongtec.zcpt.manager.APPDownloadManager;
import com.anrongtec.zcpt.manager.AppStateManager;
import com.anrongtec.zcpt.model.AppModel;
import com.anrongtec.zcpt.model.Comment;
import com.anrongtec.zcpt.model.FileId;
import com.anrongtec.zcpt.model.PageList;
import com.anrongtec.zcpt.utils.ApkUtils;
import com.anrongtec.zcpt.utils.FileUtils;
import com.anrongtec.zcpt.utils.GsonUtil;
import com.anrongtec.zcpt.utils.HttpUtil;
import com.anrongtec.zcpt.utils.ToastShow;
import com.anrongtec.zcpt.utils.Util;
import com.anrongtec.zcpt.widget.CircleImageView;
import com.anrongtec.zcpt.widget.DownloadProgressButton;
import com.anrongtec.zcpt.widget.ViewPagerToGallery;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.lzy.okhttpserver.download.DownloadService;
import com.lzy.okhttpserver.listener.DownloadListener;
import com.lzy.okhttputils.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;
import okhttp3.Response;

public class AppDetailActivity extends BaseActivity implements View.OnClickListener{
    // 应用信息
    private ImageView iv_item_app_icon;
    private TextView tv_item_app_name, tv_item_app_total_size,tv_item_app_version_name;
    private RatingBar rv_item_app_score;
    private Button btn_item_app_install;

    /**轮播图控件*/
//	private BannerView banner;
    private ViewPager vp_app_detail_banner;
    // 界面控件
    private TextView tv_app_detail_describe, tv_app_detail_update_describe;
    private AppCompatButton acb_app_detail_publish_comment, acb_app_detail_describe_more;
    private DownloadProgressButton dpb_app_detail_download;
    // 热门评论
    private CircleImageView civ_item_person_comment_avada;
    private TextView tv_item_person_comment_name, tv_item_person_comment_version, tv_item_person_comment_content,
            tv_item_person_comment_time;
    private RatingBar rating_item_person_comment;

    private Intent intent;
    /**当前app对象*/
    private AppModel appModel;
    /**当前app的评论*/
    private List<Comment> comments;
    /** 最新评论 */
    private Comment latestComments;
    /**评论页, 总页数*/
    private int currentPage = 1, totalPage;
    /**显示评论的layout*/
    private View commentsLayout;
    /**暂无评论*/
    private TextView comments_empty;

    /** 当前app的taskKey(下载任务的唯一标识)，  即该app的url地址 */
    private String appTask;
    /**当前app的downloadInfo*/
//	private DownloadInfo downloadInfo;
    /**下载管理类对象*/
    private DownloadManager downloadManager;
    /**下载管理监听*/
    private DownloadListener listener;

    /**广播接收器, 接收安装卸载*/
    private AppStateManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitleShow(true);
        super.onCreate(savedInstanceState);
        initData();
        setContentView(R.layout.activity_app_detail);
        initViews();
        initEvents();
        registerAppStatus();
    }

    /**
     * 注册广播接收器
     */
    private void registerAppStatus() {
        manager = new AppStateManager(AppDetailActivity.this);
        manager.begin(new AppStateManager.AppStateListener() {

            @Override
            public void onAppUninstalled(String pkgName) {
            }

            @Override
            public void onAppRelpaced(String pkgName) {
                dpb_app_detail_download.setState(DownloadProgressButton.OPEN);
            }

            @Override
            public void onAppInstalled(String pkgName) {
                dpb_app_detail_download.setState(DownloadProgressButton.OPEN);
            }
        });
    }


    @Override
    protected void onDestroy() {
        if(manager!=null){
            manager.unregisterListener();
        }
        super.onDestroy();
    }

    protected void onCreateCustomToolBar(Toolbar toolbar) {
        toolbar.setTitle(appModel.getAppName());
    }

    protected void initData() {

        appModel = (AppModel) getIntent().getSerializableExtra(Constant.DATA);

        appTask = appModel.getUrl();

        //获取评论信息
        getComments();

    }

    protected void initViews() {

        //应用描述
        tv_app_detail_describe = (TextView) findViewById(R.id.tv_app_detail_describe);
        //更新描述
        tv_app_detail_update_describe = (TextView) findViewById(R.id.tv_app_detail_update_describe);
        tv_app_detail_update_describe.setText(appModel.getVersionDesc());
        //评论
        acb_app_detail_publish_comment = (AppCompatButton) findViewById(R.id.acb_app_detail_publish_comment);
        //查看更多评论
        acb_app_detail_describe_more = (AppCompatButton) findViewById(R.id.acb_app_detail_describe_more);



        //include应用信息控件
        iv_item_app_icon = (ImageView) findViewById(R.id.iv_app_details_icon);
//        ImageLoader.getInstance().displayImage(appModel.getIconUrl(), iv_item_app_icon);
        Glide.with(this).load(appModel.getIconUrl()).into(iv_item_app_icon);
        tv_item_app_name = (TextView) findViewById(R.id.tv_app_details_name);
        tv_item_app_name.setText(appModel.getAppName());
        tv_item_app_total_size = (TextView) findViewById(R.id.tv_app_details_total_size);
        tv_item_app_total_size.setText(Util.byte2Mega(appModel.getSize()));
        rv_item_app_score = (RatingBar) findViewById(R.id.rv_app_details_score);
        rv_item_app_score.setRating(appModel.getScore());
        tv_item_app_version_name = (TextView) findViewById(R.id.tv_app_details_version_name);
        tv_item_app_version_name.setText(appModel.getRemoteVersionName());

        //轮播图
        setBanner();

        //下载按钮
        initDownloadButton();

        //应用描述和新版本描述
        setExpandRichText();

        initCommentsView();
    }

    /**
     * 初始化轮播图
     */
    private void setBanner() {
//		banner = (BannerView) findViewById(R.id.bv_app_details_banner);
        vp_app_detail_banner=(ViewPager) findViewById(R.id.vp_app_detail_banner);
        List<String> imageUrls = new ArrayList<String>();
        List<FileId> pics = appModel.getPics();
        for (int i = 0; i < pics.size(); i++) {
            imageUrls.add(pics.get(i).getFileId());
        }
//		ViewPagerToGallery.getInstance(AppDetailActivity.this).setImageUrls(vp_app_detail_banner, imageUrls);
        ViewPagerToGallery.getInstance().setImageUrls(this, vp_app_detail_banner, imageUrls);
//		banner.setImageResoucesUrl(imageUrls, null);

    }


    /**
     * 初始化下载按钮
     */
    private void initDownloadButton() {
        dpb_app_detail_download = (DownloadProgressButton) findViewById(R.id.dpb_app_detail_download);
        listener = new AppDownLoadListener();
        downloadManager = DownloadService.getDownloadManager();
        //根据url来获取DownloadInfo
        DownloadInfo downloadInfo = downloadManager.getDownloadInfo(appTask);
        if (downloadInfo != null) {
            //TODO  每次重新拼接下载的url
            if (downloadInfo.getProgress() != 0 && downloadInfo.getState() != DownloadManager.DOWNLOADING && downloadInfo.getState() != DownloadManager.FINISH) {
                downloadInfo.setState(DownloadManager.PAUSE);
                dpb_app_detail_download.setState(DownloadProgressButton.PAUSE);
            }else if (downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                dpb_app_detail_download.setState(DownloadProgressButton.DOWNLOADING);
            }
            downloadInfo.setUrl(Util.getDownloadUrl(appModel.getUrl()));
            downloadInfo.setListener(listener);

            refreshButtonState(downloadInfo);

        }else {
            dpb_app_detail_download.setState(DownloadProgressButton.NONE);
        }


        dpb_app_detail_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DownloadInfo info = downloadManager.getDownloadInfo(appTask);
                if (info == null) {
                    download();
                    return;
                }

                if (v.getId() != R.id.dpb_app_detail_download) {
                    return;
                }

                //点击之前按钮的状态
                switch (info.getState()) {
                    case DownloadManager.NONE:
                    case DownloadManager.ERROR:
                        //点击之前无状态，则开始下载
                        download();
                        break;
                    case DownloadManager.WAITING:

                        break;
                    case DownloadManager.DOWNLOADING:
                        //点击之前是正在下载状态，则点击之后暂停
                        downloadManager.pauseTask(appTask);
                        break;
                    case DownloadManager.PAUSE:
//					dpb_app_detail_download.setState(DownloadProgressButton.DOWNLOADING);
                        downloadManager.addTask(appTask, info.getRequest(), info.getListener());
                        break;
                    case DownloadManager.FINISH:
                        //判断该APP是否安装
                        if (ApkUtils.isInstalled(AppDetailActivity.this, appModel.getAppPackName(), appModel.getRemoteVersionCode())) {
                            //该app不是商店应用本身
                            if (!appModel.getAppPackName().equals(Util.getPackageName(AppDetailActivity.this))) {
                                ApkUtils.openAPP(AppDetailActivity.this, appModel.getAppPackName());
                            }
                        }else{
                            //判断下载安装包是否存在
                            if (FileUtils.isExist(info.getTargetPath())) {
                                ApkUtils.installSilent(AppDetailActivity.this, new File(info.getTargetPath()));
//							ApkUtils.install(AppDetailActivity.this, new File(info.getTargetPath()));
                            }else {
                                //不存在，则重新下载
                                downloadManager.removeTask(appTask);
                                download();
                            }
                        }
                        break;

                    default:
                        break;
                }
            }
        });

    }


    /**
     * 更新下载按钮状态
     */
    private void refreshButtonState(DownloadInfo info) {
        //如果不是空,说明有下载的状态!
        //判断下载状态来修改button的状态
        int state = DownloadProgressButton.NONE;
        switch (info.getState()) {
            case DownloadManager.NONE:
                state = DownloadProgressButton.NONE;

                break;
            case DownloadManager.WAITING:
                state = DownloadProgressButton.WAITING;

                break;
            case DownloadManager.DOWNLOADING:
                state = DownloadProgressButton.DOWNLOADING;
                dpb_app_detail_download.updateProgress(info.getProgress()*100);
                downloadManager.addTask(appTask, info.getRequest(), info.getListener());
                break;
            case DownloadManager.PAUSE:
                state = DownloadProgressButton.PAUSE;
                dpb_app_detail_download.updateProgress(info.getProgress()*100);
                break;
            case DownloadManager.FINISH:
                if (ApkUtils.isInstalled(AppDetailActivity.this, appModel.getAppPackName(), appModel.getRemoteVersionCode())) {
                    state = DownloadProgressButton.OPEN;
                }else {
                    if (FileUtils.isExist(info.getTargetPath())) {
                        state = DownloadProgressButton.FINISH;
                    }else {
                        state = DownloadProgressButton.NONE;
                    }
                }
                break;
            case DownloadManager.ERROR:
                state = DownloadProgressButton.ERROR;

                break;

            default:
                break;
        }
        dpb_app_detail_download.setState(state);
    }

    protected void initEvents() {
        acb_app_detail_publish_comment.setOnClickListener(this);
        acb_app_detail_describe_more.setOnClickListener(this);
    }

    /**
     * 获取当前应用的评论信息
     */
    private void getComments() {

        String json = GsonUtil.toQueryCommentJson(appModel.getAppPackName(), appModel.getRemoteVersionCode(), currentPage);
        HttpUtil.post(json, new StringCallback() {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                JsonDataRestult<PageList<Comment>> result = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<PageList<Comment>>>(){}.getType());
                if (URLConstants.RetCode.SUCCESS.equals(result.getRetCode())) {
                    currentPage = result.getData().getPage();
                    totalPage = result.getData().getTotalPage();
                    comments = result.getData().getComments();
                    if (comments != null && comments.size() != 0) {
                        latestComments = comments.get(0);//最新的一条评论
                        setComments(latestComments);
                    }
                }else {
                    ToastShow.shortMessage(result.getRetMsg());
                }
            }
        });


    }

    /**
     * 初始化评论部分控件
     */
    private void initCommentsView() {
        //评论
        commentsLayout = findViewById(R.id.app_detail_comments);//显示评论layout
        comments_empty = (TextView) findViewById(R.id.app_details_comments_empty);//无评论
        civ_item_person_comment_avada = (CircleImageView) findViewById(R.id.civ_item_person_comment_avada);//头像	无,显示本地图片
        tv_item_person_comment_name = (TextView) findViewById(R.id.tv_item_person_comment_name);//name	匿名用户
        tv_item_person_comment_version = (TextView) findViewById(R.id.tv_item_person_comment_version);//version 不显示
        tv_item_person_comment_content = (TextView) findViewById(R.id.tv_item_person_comment_content);//内容
        rating_item_person_comment = (RatingBar) findViewById(R.id.rating_item_person_comment);//评分
        tv_item_person_comment_time = (TextView) findViewById(R.id.tv_item_person_comment_time);//时间
    }

    /**
     * 设置评论
     */
    private void setComments(Comment latestComments){

        if (latestComments == null) {
            return;
        }
        commentsLayout.setVisibility(View.VISIBLE);
        comments_empty.setVisibility(View.GONE);

//		civ_item_person_comment_avada.setImageResource(R.drawable.pic_tab04);
//		tv_item_person_comment_name.setText(latestComments.getName());
        tv_item_person_comment_version.setText(latestComments.getVersion());
        tv_item_person_comment_content.setText(latestComments.getContent());
        rating_item_person_comment.setRating(latestComments.getScore());
        tv_item_person_comment_time.setText(latestComments.getTime());

        if (comments !=null && comments.size() > 1) {
            acb_app_detail_describe_more.setVisibility(View.VISIBLE);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //评论
            case R.id.acb_app_detail_publish_comment:
                intent=new Intent(this, AppCommentPublishActivity.class);
                intent.putExtra(Constant.DATA, appModel);
                startActivityForResult(intent, Constant.requestcode);
                break;

            //查看更多评论
            case R.id.acb_app_detail_describe_more:
                intent=new Intent(this, AppCommentsActivity.class);
                intent.putExtra(Constant.DATA, appModel);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Constant.resultcode) {
            Comment c = (Comment) data.getSerializableExtra(Constant.DATA);
            if (c != null) {
                setComments(c);
            }
        }
        getComments();

    }


    /**
     * 设置应用描述, 展开
     */
    private void setExpandRichText(){
        String desc = appModel.getDescription();
        if (TextUtils.isEmpty(desc)) {
            desc = "暂无应用描述。";
        }
        if(desc.length() <= 30){
            tv_app_detail_describe.setText(desc);
            return;
        }
        String zoomText=(String) appModel.getDescription().subSequence(0, 30)+"...";
        String moreText="更多";
        SpannableString spannableString = new SpannableString(zoomText+moreText);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            // 单击时要执行的动作
            public void onClick(View widget) {
                setZoomRichText();
            }
            @Override
            public void updateDrawState(TextPaint ds) {
                /**set textColor**/
                ds.setColor(ContextCompat.getColor(AppDetailActivity.this, R.color.blue_00aaee));
                /**Remove the underline**/
                ds.setUnderlineText(false);
            }
        }, zoomText.length(), zoomText.length()+moreText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_app_detail_describe.setText(spannableString);
        // 再单击链接时凡是要执行的动作都必须设置MovementMethod对象
        tv_app_detail_describe.setMovementMethod(LinkMovementMethod.getInstance());
    }
    /**
     * 设置应用描述, 收起
     */
    private void setZoomRichText(){
        String allText=appModel.getDescription()+"  ";
        String zoomText="收起";
        SpannableString spannableString = new SpannableString(allText+zoomText);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            // 单击时要执行的动作
            public void onClick(View widget) {
                setExpandRichText();
            }
            @Override
            public void updateDrawState(TextPaint ds) {
                /**set textColor**/
//		        ds.setColor(Color.parseColor("#B8860B"));
                ds.setColor(ContextCompat.getColor(AppDetailActivity.this, R.color.blue_00aaee));
                /**Remove the underline**/
                ds.setUnderlineText(false);
            }
        }, allText.length(), allText.length()+zoomText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_app_detail_describe.setText(spannableString);
        // 再单击链接时凡是要执行的动作都必须设置MovementMethod对象
        tv_app_detail_describe.setMovementMethod(LinkMovementMethod.getInstance());
    }


    /**
     * 下载
     */
    private void download() {
        APPDownloadManager.addTask(getApplicationContext(), appModel, listener);
    }


    /**
     * app下载监听
     * @author cxy
     *
     */
    class AppDownLoadListener extends DownloadListener{

        @Override
        public void onAdd(DownloadInfo downloadInfo) {
            dpb_app_detail_download.setState(DownloadProgressButton.WAITING);
        }

        @Override
        public void onProgress(DownloadInfo arg0) {
            refreshButtonState(arg0);
        }

        @Override
        public void onFinish(DownloadInfo arg0) {
            //判断该APP是否安装
//				if (ApkUtils.isAvailable(getApplicationContext(), appModel.getAppPackName())) {
            if (ApkUtils.isInstalled(AppDetailActivity.this, appModel.getAppPackName(), appModel.getRemoteVersionCode())) {
                dpb_app_detail_download.setState(DownloadProgressButton.OPEN);
            }else{
                dpb_app_detail_download.setState(DownloadProgressButton.FINISH);
            }

            //下载完成后提示安装
            if (FileUtils.isExist(arg0.getTargetPath())) {
                ApkUtils.installSilent(AppDetailActivity.this, new File(arg0.getTargetPath()));
//					ApkUtils.install(AppDetailActivity.this, new File(arg0.getTargetPath()));
            }

        }
        @Override
        public void onError(DownloadInfo arg0, String arg1, Exception arg2) {
            dpb_app_detail_download.setState(DownloadProgressButton.ERROR);
        }

    }

}

